package com.lijunjie.platform.api.shiro;

import com.lijunjie.platform.api.modules.sys.entity.Role;
import com.lijunjie.platform.api.modules.sys.entity.User;
import com.lijunjie.platform.api.modules.sys.service.IRoleService;
import com.lijunjie.platform.api.modules.sys.service.IUserService;
import com.lijunjie.platform.api.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
public class JWTRealm extends AuthorizingRealm {

    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User u = (User) principalCollection.getPrimaryPrincipal();

        Set<String> roleSet = new HashSet<>();
        //获取当前用户的所有角色
        List<Role> roleList = this.roleService.getRoleByUserId(u.getId());

        for (int i = 0; i < roleList.size(); i++) {
            roleSet.add(roleList.get(i).getRoleName());
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleSet);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        JWTToken jwtToken = (JWTToken) authenticationToken;
        String token = jwtToken.getPrincipal().toString();

        //解析token 获得用户userId 查询user信息
        String userId = JWTUtil.getUserId(token);
        User user = this.userService.getById(userId);
        if(null == user)
            throw new AuthenticationException("token 无效，请重新登录");

        //交给凭证匹配器,credentials入参为 user.getPassword()+ user.getJwtSecret(),注销修改jwtsecret,修改密码，都可以是jwt失效
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword()+ user.getJwtSecret(),"JwtRealm");

        return simpleAuthenticationInfo;
    }

}
